$(document).ready(function() {
    $('.formeditor').formEditor({
        url: "/admin/actions/processFields.php",
        form: bridge.form,
        toolset: bridge.toolset,
        settings: bridge.formsettings,
    });
});

var formEditor = {
    options: {
        form: false,
        toolset: false,
        settings: {
            block_id: 0,
            relation: "E",
        }
    },
    id: 1,
    data: [],
    _create: function() {
        var self = this;
        this.droppable = {
            scope: 'tool',
            greedy: true,
            over: function(e, ui) {
                $('.container', self.element).removeClass('over');
                $(this).children('.container').addClass('over');
            },
            drop: function(e, ui) {
                var item = $(this);
                var toolType = ui.draggable.data('toolType');
                var target = $(this).children('.container');
                $('.container', self.element).removeClass('over');
                if (target.length) {
                    var drop = self.CreateField(toolType);
                    var form = drop.children('form');
                    var parentForm = item.children('form');
                    var parentId = parentForm.children('input[name = id]').val();
                    target.append(drop);                    
                    form.children('input[name = container_id]').val(parentId);
                    self.UpdateData(form.serializeArray());
                }
            }
        };

        this.element.append(this.CreateToolBar());
        this.element.prepend(this.CreateWorkarea());
        if(this.options.form){
            var fields = this.FillForm(this.options.form);
            var target = this.element.children('.workarea');            
            target.children('.container').append(fields);
        }
    },
    CreateToolBar: function() {
        var toolbar = $('<div class="toolbar">');
        var helper = '<div class="handle">';
        var tools = this.options.toolset;
        var tool = '<div class="tool">';
        for (var i in tools) {
            var item = tools[i];
            var toolname = item.title;
            var toolPlate = $(tool).html(toolname);
            toolPlate.data("toolType", item.id);
            toolPlate.draggable({
                scope: "tool",
                handle: ".handle",
                helper: "clone",
            });
            toolbar.append(toolPlate.append(helper));
        }
        return toolbar;
    },
    CreateWorkarea: function() {
        var responder = $("<div class=\"responder\">Add fields and fill settings</div>");
        var workarea = $('<div class="workarea">').append(responder);
        var form = $('<form class="settings">');
        var self = this;
        form.append(
                "<label>Block ID: </label>",
                $('<input readonly type="text" name="block_id" size=4>').val(this.options.settings.block_id),
                "<label>Relation: </label>",
                $('<input readonly checked="checked" type="radio" name="relation" value="'+this.options.settings.relation+'" size=4>').val(this.options.settings.block_id),
                "<label>"+this.options.settings.relation+"</label>",
                "<a href=\"javascript:;\" class=\"saveForm button\">Save form</a>"
                );
        workarea.append(form, $('<div class="container">'));
        workarea.droppable(this.droppable);
        form.find('a.saveForm').click(function(){
            self.SendData();
            return false;
        });
        return workarea;
    },
    CreateField: function(tooltype, customData) {
        var self = this;
        var settings = this.options.toolset[tooltype - 1];
        var formTemplate = '<input type="hidden" name="block_id" value="' + this.options.settings.block_id + '">' +
                '<input type="hidden" name="relation" value="' + this.options.settings.relation + '">' +
                '<input type="hidden" name="exists" value="">' +
                '<input type="hidden" name="id" value="'+self.id+'">' +
                '<input type="hidden" name="field_type" value="'+settings.id+'">' +
                '<input type="hidden" name="container_id" value="">' +
                '<label>Field code</label><input type="text" name="code" value=""><br />' +
                '<label>Title</label><input type="text" name="title" value=""><br />' +
                '<label>Default value</label><input type="text" name="default_value" value=""><br />' +
                '<label>Multifield</label><input type="checkbox" name="multi"><br />' +
                '<input type="button" name="UpdateData" value="Save settings">';
        
        var fieldTemplate = '<div id="'+self.id+'" class="field"><div class="title">Type: ' + settings.title + '</div><a href="javascipt:;" class="switchForm">Settings</a><a href="javascipt:;" class="dropField">Drop field</a><div class="field-responder">Save settings</div><form>' + formTemplate + '</form></div>';
        self.id++;
        var field = $(fieldTemplate);
        if (settings.is_container) {
            var container = $('<div class="container">');
            field.droppable(this.droppable);
            field.append(container);
        }
        var form = field.children('form');
        field.find('.switchForm').click(function() {
            field.children('form').toggleClass('visible');
            return false;
        });
        field.find('.dropField').click(function() {
            field.remove();
            self.UpdateData(field.children('form').serializeArray(), true);
            return false;
        });
        var responder = field.children('.field-responder');
        form.children('input[name=UpdateData]').click(function() {
            responder.html("Settings applied").addClass('ok');
            self.UpdateData(field.children('form').serializeArray());
            return false;
        });
        form.children('input[name != UpdateData]').focus(function(){
            responder.html("Save settings").removeClass('ok');
        });
        if(customData){
            field.attr("id", customData.id);
            form.children('input[name = id]').val(customData.id);
            form.children('input[name = container_id]').val(customData.container_id);
            form.children('input[name = code]').val(customData.code);
            form.children('input[name = title]').val(customData.title);
            form.children('input[name = field_type]').val(customData.field_type);
            form.children('input[name = default_value]').val(customData.default_value);
            form.children('input[name = multi]').prop("checked",(customData.multi ? true : false));
            form.children('input[name = exists]').val(1);            
            self.UpdateData(form.serializeArray());
        }
        return field;
    },
    FillForm: function(data){
        var root = $('<div class="tmp">');
        for(var i in data){
            var fieldData = data[i];
            var toolType = fieldData.field_type;
            var field = this.CreateField(toolType, fieldData);
            var form = field.children('form');
            root.append(field);
        }
        
        root.children().each(function(){
            var item = $(this);
            var form = item.children('form');
            var id = form.children('input[name = container_id]').val();
            if(id){
                var target = root.find('div#'+id);
                target.children('.container').append(item);
            }
        });
        
        return root.children();
    },
    UpdateData: function(formData, remove) {
        var data = {};
        
        for (var i in formData) {
            data[formData[i].name] = formData[i].value;
        }
        
        var targetId = false;
        
        for (var j in this.data) {
            if(this.data[j].id == data.id){
                targetId = j;
                break;
            }
        }
        
        if(!targetId){
            this.data.push(data);            
        }else{
            if(remove){
                if(data.exists){
                    this.data[targetId] = {
                        id: data.id,
                        exists: data.exists,
                        drop: 1,
                    }
                }else{
                    this.data.splice(targetId);
                }
            }else{
                this.data[targetId] = data;
            }
        } 
        
    },
    SendData: function(){
        var responder = this.element.find('.workarea .responder');
        
        $.ajax({
            url: this.options.url,
            dataType: "json",
            type: "POST",
            data: {fields: this.data},
            beforeSend: function(resp){
                responder.removeClass("ok").removeClass("error");
                responder.addClass("process").html("Processing data...");
            },
            success: function(resp){
                responder.removeClass("ok").removeClass("error").removeClass("process");
                responder.addClass(resp.type).html(resp.msg);
                console.log(resp);
            },
            error: function(){
                responder.removeClass("ok").removeClass("error").removeClass("process");
                responder.addClass("error").html("Fatal error. Data not saved. Please, try again later");
            }
        });
    }
};

$.widget("frost.formEditor", formEditor);